// (c) Copyright 2013 Stephen Gold <sgold@sonic.net>
// Distributed under the terms of the GNU General Public License

/*
 This file is part of the Bats Game.

 The Bats Game is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by the
 Free Software Foundation, either version 3 of the License, or (at your
 option) any later version.

 The Bats Game is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 for more details.

 You should have received a copy of the GNU General Public License
 along with the Bats Game.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * vertex shader used by matte.j3md
 */
attribute vec2 inTexCoord;
attribute vec3 inNormal;
attribute vec3 inPosition;
attribute vec4 inTangent;

uniform mat3 g_NormalMatrix;
uniform mat4 g_ViewMatrix;
uniform mat4 g_WorldViewMatrix;
uniform mat4 g_WorldViewProjectionMatrix;

uniform vec4 g_AmbientLightColor;
uniform vec4 g_LightColor;
uniform vec4 g_LightPosition;

varying vec2 texCoord;

varying vec3 AmbientSum;
varying vec3 DiffuseSum;
varying vec3 lightVec;
varying vec3 vNormal;

varying vec4 vLightDir;

// JME3 lights in world space
void lightComputeDir(in vec3 worldPos, in vec4 color, in vec4 position, out vec4 lightDir) {
    float posLight = step(0.5, color.w);
    vec3 tempVec = position.xyz * sign(posLight - 0.5) - (worldPos * posLight);
    lightVec = tempVec;
    float dist = length(tempVec);
    lightDir.w = clamp(1.0 - position.w * dist * posLight, 0.0, 1.0);
    lightDir.xyz = tempVec / dist;
}

void main() {
    texCoord = inTexCoord;
    vNormal = normalize(g_NormalMatrix * inNormal);

    vec4 modelSpacePos = vec4(inPosition, 1);
    gl_Position = g_WorldViewProjectionMatrix * modelSpacePos;

    vec3 wvPosition = (g_WorldViewMatrix * modelSpacePos).xyz;
    vec4 wvLightPos = g_ViewMatrix * vec4(g_LightPosition.xyz, clamp(g_LightColor.w, 0.0, 1.0));
    wvLightPos.w = g_LightPosition.w;
    lightComputeDir(wvPosition, g_LightColor, wvLightPos, vLightDir);

    AmbientSum = g_AmbientLightColor.rgb;
    DiffuseSum = g_LightColor.rgb;
}